/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.lizg.Model;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author LizG
 */
public class Receive {

    private BufferedOutputStream bos;
    private ServerSocket serversocket;
    private Socket s;
    private int len;
    private BufferedInputStream bis;
    
    private static String file = null;
    //get_set_
    public void setFile(String file) {
        Receive.file = file;
    }

    public void receive() {
        try {  
            serversocket = new ServerSocket(8089);
            System.out.println("正在接受。。。");
            s = serversocket.accept();
            System.out.println("连接成功");
            System.out.println("file:" + file);
            bis = new BufferedInputStream(s.getInputStream());
            //封装文件到输入流中
            bos = new BufferedOutputStream(new FileOutputStream(file));
            System.out.println("封装文件到输入流中完成");
            //封装通道中的流
            //把文件中的流传入通道中   文件--->InStream---->OutStream(通道)
           
            System.out.println("封装通道中的流");
            //System.out.println("……");
            
            byte[] bys = new byte[2048];
            len = 0;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys, 0, len);
                bos.flush();
            }
            System.out.println("写入本地完成");
            
        } catch (IOException ex) {
            Logger.getLogger(Send.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                //释法
                bos.close();
                bis.close();
                s.close();
                serversocket.close();
            System.out.println("释放socket完成");
            } catch (IOException ex) {
                Logger.getLogger(Receive.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
